<template>
  <div class="second-hand-management">
    <!-- 操作栏 -->
    <div class="operation-bar">
      <el-input
        v-model="searchText"
        placeholder="搜索商品"
        style="width: 300px"
        clearable
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>添加商品
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-table :data="filteredProducts" border style="width: 100%">
      <el-table-column prop="productId" label="商品编号" width="120" sortable />
      <el-table-column prop="productName" label="商品名称" width="150" />
      <el-table-column prop="category" label="类别" width="120" />
      <el-table-column prop="price" label="价格（元）" width="100" sortable />
      <el-table-column prop="status" label="状态" width="80">
        <template #default="{ row }">
          {{ row.status === 'onSale' ? '在售' : '已售出' }}
        </template>
      </el-table-column>
      <el-table-column prop="description" label="商品描述" width="200" />
      <el-table-column prop="stock" label="库存数量" width="100" sortable />
      <el-table-column prop="publishDate" label="发布日期" width="120" sortable />
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(row.productId)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditMode ? '编辑商品信息' : '添加新商品'"
      width="600"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="商品编号" prop="productId">
          <el-input v-model="formData.productId" :disabled="isEditMode" />
        </el-form-item>
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="formData.productName" />
        </el-form-item>
        <el-form-item label="类别" prop="category">
          <el-input v-model="formData.category" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number
            v-model="formData.price"
            :min="0"
            :step="0.01"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio label="onSale">在售</el-radio>
            <el-radio label="soldOut">已售出</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input type="textarea" v-model="formData.description" rows="3" />
        </el-form-item>
        <el-form-item label="库存数量" prop="stock">
          <el-input-number
            v-model="formData.stock"
            :min="0"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="发布日期" prop="publishDate">
          <el-date-picker
            v-model="formData.publishDate"
            type="date"
            placeholder="选择发布日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm"> 确认 </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 初始测试数据（10 条二手商品数据）
const products = ref([
  {
    productId: 'SP2023001',
    productName: '九成新笔记本电脑',
    category: '电子产品',
    price: 3500.00,
    status: 'onSale',
    description: 'Intel i5处理器，8GB内存，512GB固态',
    stock: 1,
    publishDate: '2023-09-01'
  },
  {
    productId: 'SP2023002',
    productName: '实木书桌',
    category: '家具家居',
    price: 800.00,
    status: 'soldOut',
    description: '1.2米实木书桌，带抽屉',
    stock: 0,
    publishDate: '2023-09-02'
  },
  {
    productId: 'SP2023003',
    productName: '考研复习资料',
    category: '书籍教材',
    price: 150.00,
    status: 'onSale',
    description: '包含历年真题和笔记',
    stock: 3,
    publishDate: '2023-09-03'
  },
  {
    productId: 'SP2023004',
    productName: '闲置自行车',
    category: '交通工具',
    price: 200.00,
    status: 'onSale',
    description: '轻便折叠自行车，适合城市通勤',
    stock: 1,
    publishDate: '2023-09-04'
  },
  {
    productId: 'SP2023005',
    productName: '旧款智能手机',
    category: '电子产品',
    price: 800.00,
    status: 'soldOut',
    description: '某品牌旧款手机，性能尚可',
    stock: 0,
    publishDate: '2023-09-05'
  },
  {
    productId: 'SP2023006',
    productName: '冬季羽绒服',
    category: '服装配饰',
    price: 300.00,
    status: 'onSale',
    description: '中长款羽绒服，保暖性好',
    stock: 2,
    publishDate: '2023-09-06'
  },
  {
    productId: 'SP2023007',
    productName: '健身哑铃套装',
    category: '运动器材',
    price: 150.00,
    status: 'onSale',
    description: '多种重量哑铃组合',
    stock: 1,
    publishDate: '2023-09-07'
  },
  {
    productId: 'SP2023008',
    productName: '复古留声机',
    category: '家居摆件',
    price: 500.00,
    status: 'onSale',
    description: '具有复古风格的留声机',
    stock: 1,
    publishDate: '2023-09-08'
  },
  {
    productId: 'SP2023009',
    productName: '儿童玩具套装',
    category: '玩具',
    price: 80.00,
    status: 'onSale',
    description: '包含多种玩具的套装',
    stock: 3,
    publishDate: '2023-09-09'
  },
  {
    productId: 'SP2023010',
    productName: '二手相机镜头',
    category: '摄影器材',
    price: 1200.00,
    status: 'onSale',
    description: '某品牌镜头，成像效果好',
    stock: 1,
    publishDate: '2023-09-10'
  }
])

// 搜索功能
const searchText = ref('')
const filteredProducts = computed(() => {
  return products.value.filter(product => {
    return Object.values(product).some(value =>
      String(value).toLowerCase().includes(searchText.value.toLowerCase()))
  })
})

// 对话框相关状态
const dialogVisible = ref(false)
const isEditMode = ref(false)
const formRef = ref(null)
const formData = reactive({
  productId: '',
  productName: '',
  category: '',
  price: 0,
  status: 'onSale',
  description: '',
  stock: 0,
  publishDate: ''
})

// 表单验证规则
const formRules = {
  productId: [{ required: true, message: '请输入商品编号', trigger: 'blur' }],
  productName: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  category: [{ required: true, message: '请输入商品类别', trigger: 'blur' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }, { type: 'number', message: '请输入有效数字' }],
  stock: [{ required: true, message: '请输入库存数量', trigger: 'blur' }, { type: 'number', message: '请输入有效数字' }],
  publishDate: [{ required: true, message: '请选择发布日期', trigger: 'change' }]
}

// 处理添加
const handleAdd = () => {
  isEditMode.value = false
  resetForm()
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row) => {
  isEditMode.value = true
  Object.assign(formData, { ...row })
  dialogVisible.value = true
}

// 处理删除
const handleDelete = (productId) => {
  ElMessageBox.confirm('确定要删除该商品吗？', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    products.value = products.value.filter(p => p.productId !== productId)
    ElMessage.success('删除成功')
  })
}

// 提交表单
const submitForm = async () => {
  await formRef.value.validate()
  if (isEditMode.value) {
    // 更新数据
    const index = products.value.findIndex(
      p => p.productId === formData.productId
    )
    products.value.splice(index, 1, { ...formData })
  } else {
    // 添加数据
    products.value.push({ ...formData })
  }
  dialogVisible.value = false
  ElMessage.success(isEditMode.value ? '修改商品成功' : '添加商品成功')
}

// 重置表单
const resetForm = () => {
  formData.productId = ''
  formData.productName = ''
  formData.category = ''
  formData.price = 0
  formData.status = 'onSale'
  formData.description = ''
  formData.stock = 0
  formData.publishDate = ''
}
</script>

<style scoped>
.second-hand-management {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.operation-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 15px;
}

.el-table {
  margin-top: 20px;
}

.el-textarea__inner {
  height: 80px;
}
</style>
    